package com.smart.common.utils.task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 之对于大于一分钟的任务使用redis锁，防止任务重复执行
 */
@Component
public class TaskUtils {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //加入任务
    public void addTask(String taskId,Long timeOut,TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(taskId, taskId, timeOut,timeUnit);
    }

    /**
     * 判断任务是否存在
     * @param taskId
     * @return 存在返回true
     */
    public boolean isTaskExist(String taskId) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(taskId));
    }

    //手动释放锁
    public void releaseTask(String taskId) {
        redisTemplate.delete(taskId);
    }
}
